package common

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
)

type Functions struct {

}

//发送数据
func (that *Functions) SendMsg(conn net.Conn, data []byte) (err error){
	//获取长度
	sendMsgLen := uint32(len(data))
	//转为切片
	var sendMsgLenByte =  make([]byte,4)
	binary.BigEndian.PutUint32(sendMsgLenByte,sendMsgLen)//sedMsgLenByte = [0 0 0 996]
	//发送长度
	_, err = conn.Write(sendMsgLenByte)
	if err != nil {
		errStr := fmt.Sprintf("发送长度失败：%v",err)
		err = errors.New(errStr)
		return
	}
	//发送数据
	_, err = conn.Write(data)
	if err != nil {
		errStr := fmt.Sprintf("发送数据失败：%v",err)
		err = errors.New(errStr)
		return
	}
	return
}

//读取数据
func (that *Functions) ReadMsg(conn net.Conn) (msg *Message, err error){
	var lenByte = make([]byte,4)
	//读取长度
	_, err = conn.Read(lenByte)
	if err != nil {
		if err == io.EOF {
			errStr := fmt.Sprintf("客户端断开连接：%v",conn.RemoteAddr())
			err = errors.New(errStr)
		}else{
			errStr := fmt.Sprintf("读取长度失败：%v",err)
			err = errors.New(errStr)
		}
		return
	}

	//读取数据
	dataLen := binary.BigEndian.Uint32(lenByte)//得到数据长度
	var data = make([]byte,dataLen)
	n, err := conn.Read(data)
	if err != nil {
		if err == io.EOF {
			errStr := fmt.Sprintf("客户端断开连接：%v",conn.RemoteAddr())
			err = errors.New(errStr)
		}else{
			errStr := fmt.Sprintf("读取数据失败：%v",err)
			err = errors.New(errStr)
		}
		return
	}
	if n != int(dataLen) {
		err = errors.New("实际读取长度与应读长度不符")
		return
	}
	//转成 Message 结构体
	err = json.Unmarshal(data,&msg)
	if err != nil {
		errStr := fmt.Sprintf("转成 Message 结构体失败：%v",err)
		err = errors.New(errStr)
		return
	}
	return
}